<template>
  <div class="login-wrapper">
    <el-card class="login-card" shadow="always">
      <h2 class="login-title">连接 SuperDB 后端</h2>
      <p class="login-subtitle">请输入后端提供的 API Key 以继续。</p>
      <el-form ref="formRef" :model="form" label-position="top">
        <el-form-item label="API Key" prop="apiKey" :rules="[{ required: true, message: '必填' }]">
          <el-input v-model="form.apiKey" type="password" show-password placeholder="superdb-xxxx" />
        </el-form-item>
        <el-form-item label="后端地址">
          <el-input v-model="form.baseUrl" placeholder="默认使用 /api" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="submit">连接</el-button>
        </el-form-item>
      </el-form>
      <el-alert type="info" show-icon>
        <template #title>提示</template>
        <p>默认开发环境后端在 <code>http://localhost:4000</code> 运行，可通过根目录 README 查看。</p>
      </el-alert>
    </el-card>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useConfigStore } from '@/stores/config';

const router = useRouter();
const route = useRoute();
const config = useConfigStore();
config.loadFromStorage();

const formRef = ref();
const loading = ref(false);
const form = reactive({
  apiKey: config.apiKey,
  baseUrl: config.baseUrl
});

async function submit() {
  await formRef.value.validate();
  loading.value = true;
  try {
    config.setApiKey(form.apiKey);
    if (form.baseUrl) {
      config.baseUrl = form.baseUrl;
      config.persist();
    }
    const redirect = route.query.redirect || '/';
    router.push(redirect);
  } finally {
    loading.value = false;
  }
}
</script>

<style scoped>
.login-wrapper {
  min-height: calc(100vh - 64px);
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #409eff 0%, #67c23a 100%);
  padding: 24px;
}

.login-card {
  width: 420px;
  max-width: 100%;
}

.login-title {
  margin: 0 0 8px;
  text-align: center;
}

.login-subtitle {
  text-align: center;
  margin-bottom: 24px;
  color: #909399;
}
</style>
